public class Solution {
    public static int strStr(String haystack, String needle) {
        int len1 = haystack.length();
        int len2 = needle.length();
        if (len1 < len2) {
            return -1;
        }
        int[] next = new int[len2];
        int j = 0;
        next = getNext(needle);
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                int tmp = i;
                while(tmp < haystack.length()&& j < needle.length()&&haystack.charAt(tmp) == needle.charAt(j)) {
                    tmp++;
                    j++;
                    if (j == needle.length() ) {
                        return i;
                    }
                }

            } else {
                if (j >= 1) {
                    j = next[j-1];
                } else {
                    j = 0;
                }

            }
        }
        return -1;
    }

    public static int[] getNext(String needle) {
        int j = 0;
        int len = needle.length();
        int[] next = new int[len];
        next[0] = 0;
        for (int i = 1; i < len; i++) {
            while (j > 0 && needle.charAt(j) != needle.charAt(i)) {
                j = next[j - 1]; // 不相等的情况下回退
            }
            if (needle.charAt(j) == needle.charAt(i)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static void main(String[] args) {
        String s1 = "aabaabaaf";
        String s2 = "aabaaf";
        int ret = strStr(s1,s2);
        System.out.println(ret);
    }
}